<?php

declare (strict_types=1);

namespace App\Model;

/**
 * @property int $id
 * @property int $aid
 * @property int $uid
 * @property int $follow
 * @property int $create_time
 * @property int $unfollow_time
 */
class UserFollow extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user_follow';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'aid' => 'integer', 'uid' => 'integer', 'follow' => 'integer', 'create_time' => 'integer', 'unfollow_time' => 'integer'];

    /**
     * 我的关注列表
     * @param $uid
     * @return array
     */
    public static function getFollowList($uid)
    {


        $select = "zx_b.uid,zx_b.name as nickname,zx_d.username as num,zx_b.type,zx_b.direction,zx_c.head,ifnull(zx_d.online,0) as online,ifnull(zx_d.service_status,0) as service_status";
        $model = ConsultantDatum::from('user_follow as a')
            ->rightJoin('consultant_datum  as b', 'a.aid', '=', 'b.uid')
            ->leftJoin('user_datum as c', 'a.aid', '=', 'c.id')
            ->leftJoin('chat_user as d', 'd.uid', '=', 'a.aid')
            ->where(['a.uid' => $uid, 'b.status' => 1,'a.follow'=>1])
            ->selectRaw($select)
            ->orderBy('a.create_time', 'desc');


        return page($model);

    }


    /**
     * 改变关注状态
     * @param $uid
     * @param $aid
     * @return bool
     */
    public static function followWith($uid, $aid)
    {

        $info = self::where(['uid' => $uid, 'aid' => $aid])->first();

        if (is_null($info)) {//首次关注
            $insertData = [
                'aid' => $aid,
                'uid' => $uid,
                'follow' => 1,
                'create_time' => time(),
            ];
            $rel = self::insert($insertData);
        } else {

            if ($info['follow'] == 1) {//取消关注
                $info->follow = 0;
                $info->unfollow_time = time();
            } else {//再次关注
                $info->follow = 1;
                $info->create_time = time();
            }
            $rel = $info->save();
        }
        if ($rel) {
            return true;
        } else {
            return false;
        }

    }
}
